import { CsFundDouble } from "../common/csFundDouble";
import { Engine } from "../engine";
import { OtherFeeType } from "./otherFeeType";
import { OtherFundDouble } from "./otherFundDouble";

// 采购销售单中不同贵金属收付账单金额

export class OrderOtherFundData {
    constructor() {
        this._otherFeeList = [];  // SelfDefFundDouble
    }
    /**
 * Get the count of OtherFeeType objects
 * @returns {number}
 */
    get length() {
        return this._otherFeeList.length;
    }
    /**
     * Get the list of OtherFeeType objects
     * @returns {Array<OtherFundDouble>}
     */
    get otherFeeList() {
        return this._otherFeeList;
    }

    // CsFundDouble
    get value() {
        return new CsFundDouble(this._otherFeeList.reduce((acc, cur) => acc + cur.fundDouble.value, 0));
    }

    // 获取其他费用字符串
    getOtherFeeString() {
        return this._otherFeeList.map(item => item.otherFeeType.name + ":" + item.fundDouble.value).join(",");
    }

    /**
     * Add a OtherFeeType to the list
     * Ensures uniqueness by selfDefFundAccountType.id
     * @param {OtherFundDouble} otherFundDouble - The object to add
     * @returns {boolean} - True if added, false if duplicate ID exists
     */
    addOtherFeeFundAccount(otherFundDouble) {
        if (!otherFundDouble || !otherFundDouble.otherFeeType) {
            return false;
        }

        const typeId = otherFundDouble.otherFeeType.id;

        // Check if an item with the same type ID already exists
        // code 相同也视同相同，其他费用含了 code  都是常用费用，有系统定义
        // 但是不同的商户，其id 可能不同
        const existingIndex = this._otherFeeList.findIndex(item =>
            item.otherFeeType && (item.otherFeeType.id === typeId ||
                (otherFundDouble.otherFeeType.code != null &&
                    item.otherFeeType.code === otherFundDouble.otherFeeType.code))
        );

        if (existingIndex >= 0) {
            // Replace existing item with the new one            
            return false;
        } else {
            // Add new item
            this._otherFeeList.push(otherFundDouble);
            return true;
        }
    }

    /**
     * Remove a OtherFeeType by OtherFeeFundAccountType ID
     * @param {string} typeId - The ID of the OtherFeeFundAccountType to remove
     * @returns {boolean} - True if removed, false if not found
     */
    removeOtherFeeFundAccountById(typeId) {
        const initialLength = this._otherFeeList.length;
        this._otherFeeList = this._otherFeeList.filter(item =>
            !item.otherFeeType || item.otherFeeType.id !== typeId
        );
        return this._otherFeeList.length < initialLength;
    }

    /**
     * Remove a OtherFeeType by object reference
     * @param {OtherFeeType} otherFeeType - The object to remove
     * @returns {boolean} - True if removed, false if not found
     */
    removeOtherFeeFundAccount(otherFundDouble) {
        const initialLength = this._otherFeeList.length;
        const typeId = otherFundDouble.otherFeeType?.id;

        if (!typeId) {
            return false;
        }

        this._otherFeeList = this._otherFeeList.filter(item =>
            !item.otherFeeType || item.otherFeeType.id !== typeId
        );
        return this._otherFeeList.length < initialLength;
    }

    /**
     * Get a OtherFeeType by OtherFeeFundAccountType ID
     * @param {string} typeId - The ID of the OtherFeeFundAccountType to find
     * @returns {OtherFeeType|null} - The found object or null
     */
    getOtherFeeFundAccountById(typeId) {
        return this._otherFeeList.find(item =>
            item.otherFeeType && item.otherFeeType.id === typeId
        ) || null;
    }

    getOtherFeeFundAccountByCode(code) {
        return this._otherFeeList.find(item =>
            item.otherFeeType && item.otherFeeType.code === code
        ) || null;
    }

    /**
     * Check if a OtherFeeType with the given type ID exists
     * @param {string} typeId - The ID of the OtherFeeFundAccountType to check
     * @returns {boolean} - True if exists, false otherwise
     */
    hasOtherFeeFundAccount(typeId) {
        return this._otherFeeList.some(item =>
            item.otherFeeType && item.otherFeeType.id === typeId
        );
    }



    /**
     * Clear all OtherFeeType objects
     */
    clear() {
        this._otherFeeList = [];
    }

    /**
     * Clone this OrderOtherFeeFundData object
     * @returns {OrderOtherFeeFundData}
     */
    clone() {
        const cloned = new OrderOtherFeeFundData();
        cloned._otherFeeList = this._otherFeeList.map(item => {
            // Assuming OtherFeeType has a clone method or we create a new instance
            return OtherFundDouble.clone(item);
        });
        return cloned;
    }

    /**
     * Create from JSON
     * @param {Array} jsonStr -这是jsonStr  是json 字符串，需要先转换为json 对象
     * @returns {OrderOtherFeeFundData}
     */
    static fromJson(jsonStr) {

        if (!jsonStr) {
            return null;
        }

        let json = JSON.parse(jsonStr);

        let orderOtherFeeFundData = new OrderOtherFundData();
        if (Array.isArray(json)) {

            orderOtherFeeFundData._otherFeeList = json.map((item) => {
                return OtherFundDouble.fromJson(item);
            });
        }
        return orderOtherFeeFundData;
    }

    /**
     * Convert to JSON
     * @returns {Array} - Array of JSON representations
     */
    toJson() {

        // 过滤掉 item 中 item.fundDouble 为null 的值
        let valideList = this._otherFeeList.filter(item => item.fundDouble != null);

        return valideList.map(item => item.toJson());
    }

    toJsonStr() {
        return JSON.stringify(this.toJson());
    }
}